package com.example.asus.mydiary;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.asus.Test.Diary;
import com.example.asus.db.domain.Password;
import com.example.asus.db.gen.PasswordDao;
import com.example.asus.db.service.GreenDaoManager;

import java.util.List;

public class FirstTime extends AppCompatActivity {
    private EditText firetPsw = null;
    private EditText firetCheckPsw = null;
    private Button firbtnCommit = null;
    private Password password;
    private PasswordDao passwordDao;
    private String psw;
    private String checkpsw;
    private List<Password> check; // 用于检查当前是否已经设置密码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_time);
        // 初始化控件
        firetPsw = (EditText)findViewById(R.id.ft_psw);
        firetCheckPsw = (EditText)findViewById(R.id.ft_checkpsw);
        firbtnCommit = (Button)findViewById(R.id.ft_btncommit);

        GreenDaoManager.InitDao(this,"password.db");
        passwordDao = GreenDaoManager.getDaoSession().getPasswordDao();
        List<Password>check = passwordDao.loadAll();

        if(check.size()!=0){
            Intent intent = new Intent(FirstTime.this,SecondTime.class);
            startActivity(intent);
            finish();
        }
        else{
            firbtnCommit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    insertPsw();
                }
            });
        }
    }

    public void insertPsw(){
        psw = firetPsw.getText().toString();
        checkpsw = firetCheckPsw.getText().toString();

        // 检查密码是否为空
        if(psw.equals("")||checkpsw.equals("")){
            Toast.makeText(FirstTime.this,"请检查是否输入密码！",Toast.LENGTH_LONG).show();
        }
        else{
            // 检查两次输入是否一致
            if (psw.equals(checkpsw)){
                password = new Password(psw);
                GreenDaoManager.InitDao(this,"password.db");
                passwordDao = GreenDaoManager.getDaoSession().getPasswordDao();
                passwordDao.insert(password);  //将密码存入数据库并跳转到日记页面

                Intent intent = new Intent(FirstTime.this,DiaryRecycler.class);
                startActivity(intent);
                finish();
            }
            else {
                Toast.makeText(FirstTime.this,"请检查密码是否一致！",Toast.LENGTH_LONG).show();
            }
        }
    }


}
